package com.wzg.appframe.action;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.JsonObject;
import com.wzg.appframe.net.VolleyRequest;
import com.wzg.appframe.receiver.DownloadReceiver;
import com.wzg.appframe.utils.DownloadManagerUtil;
import com.wzg.appframe.utils.GsonUtil;
import com.wzg.appframe.utils.TLog;
import com.wzg.appframe.web.local.LocalResInit;

import java.io.File;
import java.io.UnsupportedEncodingException;

public class UpdateAction extends BaseAction {
    public UpdateAction(Context context) {
        super(context);
    }

    @Override
    public void postCallBack(String method, Object data) {

    }

    public void checkUpdate() {
        setReceiver();
        VolleyRequest request = new VolleyRequest(VolleyRequest.Method.GET, "", new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {
                try {
                    String updateInfo = new String(response.getBytes("8859_1"), "UTF-8");
                    JsonObject obj = GsonUtil.getObject(updateInfo);
                    String updateUrl = obj.get("url").getAsString();
                    String version = obj.get("version").getAsString();
                    String tips = obj.get("tips").getAsString();
                    alertUpdateTips(updateUrl, version, tips);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                TLog.d("update onErrorResponse=" + error.getMessage());
            }
        }, this.activity);
//        request.start();
//        alertUpdateTips("https://oa.epoint.com.cn/EMP7/rest/file/release?a=6a0c369e-e6ff-46fe-bf6e-5bebc1209f29;5", "7.0.0", "test update apk");
    }

    boolean isRegisterReceiver;
    DownloadReceiver receiver;

    /**
     * 注册下载成功的广播监听
     */
    private void setReceiver() {
        if (!isRegisterReceiver) {
            receiver = new DownloadReceiver();
            IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            this.activity.registerReceiver(receiver, intentFilter);
            isRegisterReceiver = true;
        }
    }

    public void unRegisterDownload() {
        this.activity.unregisterReceiver(receiver);
    }


    public static String apkPath;

    private void alertUpdateTips(final String url, final String version, final String tips) {
        TLog.d("url=" + url);
        TLog.d("version=" + version);
        TLog.d("tips=" + tips);
        try {
            String currentVersion = getVersionName();

            if (!currentVersion.equals(version)) {
                apkPath = LocalResInit.resPath + "/pda_v" + version + ".apk";
                File file = new File(apkPath);
                if (file.exists()) {
                    file.delete();
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(this.activity);
                builder.setTitle("新版本：v_" + version);
                builder.setMessage(tips);

                // 设置正按钮

                builder.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        new DownloadManagerUtil(activity).download(url, "条码通更新_v"+version, version);
                    }

                });

// 设置负按钮

                builder.setNegativeButton("稍后在说", new DialogInterface.OnClickListener() {

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

//                        enterHome();

                    }

                });

                builder.show();


            } else {
                TLog.d("no update");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getVersionName() throws Exception {
        // 获取packagemanager的实例
        PackageManager packageManager = this.activity.getPackageManager();
        // getPackageName()是你当前类的包名，0代表是获取版本信息
        PackageInfo packInfo = packageManager.getPackageInfo(this.activity.getPackageName(), 0);
        String version = packInfo.versionName;
        return version;
    }

}
